package cn.shyouchi.wuguanjia.android.components.storage;

import android.content.Context;
import android.content.SharedPreferences;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.shyouchi.wuguanjia.android.event.NeedRefreshUserEvent;
import cn.shyouchi.wuguanjia.android.event.UserDataChangeEvent;
import cn.shyouchi.wuguanjia.android.model.UserData;
import io.realm.Realm;

/**
 * Created by Eenie on 2016/10/20 at 13:11
 * Email: 472279981@qq.com
 * Des:
 */

public class UserStorage {

    public static final String STORAGE_NAME = "user";
    public static final String FIELD_NAME_TOKEN = "token";
    private Context mContext;
    private String mToken = "";
    private SharedPreferences mPreferences;
    private UserData mUserData;


    public UserStorage(Context context) {
        this.mContext = context;
        mPreferences = mContext.getSharedPreferences(STORAGE_NAME, Context.MODE_PRIVATE);
        load();
        EventBus.getDefault().register(this);
    }

    public String getToken() {
        return mToken;
    }

    private void load() {
        mToken = mPreferences.getString(FIELD_NAME_TOKEN, "");
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        mUserData = realm.where(UserData.class).equalTo("token", mToken).findFirst();
        realm.commitTransaction();
    }

    public void save(String token, UserData userData) {
        this.mToken = token;
        this.mUserData = userData;
        mPreferences.edit().putString(FIELD_NAME_TOKEN, token).apply();
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.insertOrUpdate(userData);
        realm.commitTransaction();
    }

    public void clear() {
        mPreferences.edit().clear().apply();
        if (mUserData != null) {
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            mUserData.deleteFromRealm();
            realm.commitTransaction();
        }
    }

    public UserData getUserData() {
        return mUserData;
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onUserDataChange(UserDataChangeEvent event) {
        load();
        EventBus.getDefault().post(new NeedRefreshUserEvent());
    }


    /**
     * 释放
     */
    public void detach() {
        EventBus.getDefault().unregister(this);
    }


}
